﻿using Nest;
using XYS.Core.Models;
using XYS.Core.Util;
using XYS.Service.Core.Models.APILoggerModels;
using XYS.Service.Core.Util.Helper;

namespace XYS.Core.Service.APILoggerService.LoggerWriters
{
    /// <summary>
    /// ElasticSearch 通道
    /// </summary>
    public class ElasticSearchCannel : IAPILogChannel
    {
        private readonly Nest.IElasticClient client;
        /// <summary>
        /// 
        /// </summary>
        public ElasticSearchCannel(IElasticClient client)
        {
            this.client = client;
        }


        /// <summary>
        /// 进入通道
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ResultModel EnterCannel<T>(IEnumerable<T> request) where T : class, IApiPathField, IResponseBodyField
        {
            if (string.IsNullOrWhiteSpace(GlobalCoreSetting.ApiLoggerSetting.ElasticSearchSetting.IndexName)) return ResultModel.Success;
            List<IBulkOperation> bulkOperations = request.Select(x => new BulkIndexOperation<T>(x) as IBulkOperation).ToList();
            var result = LogHelperSetting.ESClient.Bulk(new BulkRequest($"{GlobalCoreSetting.ApiLoggerSetting.ElasticSearchSetting.IndexName}-{DateTime.Now:yyyy.MM.dd}")
            {
                Operations = bulkOperations
            });
            if (result.Errors || result.ServerError?.Error != null)
                return ResultModel.Failed("Bulk失败", 400);
            return ResultModel.Success;
        }




        /// <summary>
        /// 进入通道
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task EnterCannel<T>(T request) where T : class, IApiPathField, IResponseBodyField
        {
            if (string.IsNullOrWhiteSpace(GlobalCoreSetting.ApiLoggerSetting.ElasticSearchSetting.IndexName)) return;
            //await client.BulkAsync($"{defaultIndex}-{DateTime.Now:yyyy.MM.dd}", request).ConfigureAwait(false);
            var bulkResponse = await client.BulkAsync(new BulkRequest($"{GlobalCoreSetting.ApiLoggerSetting.ElasticSearchSetting.IndexName}-{DateTime.Now:yyyy.MM.dd}")
            {
                Operations = new List<IBulkOperation>() { new BulkIndexOperation<T>(request) }
            });
        }



    }
}
